package com.ohuang.util_a.task;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 超时自动回调
 */
public class TimeTask extends Task {


    private Task mTask;
    //任务超时时间
    private long timeOut = 0;
    private Timer timer;



    public TimeTask(Task mTask, long timeOut) {
        this.mTask=mTask;
        this.timeOut = timeOut;
    }

    @Override
    public void run(TaskCallBack taskCallBack) {
        TaskCallBack taskCallBack1 = new OnceTaskCallBack() {
            @Override
            public void onCall() {
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                taskCallBack.onNext();
                mTask.setStop(true);
            }
        };
        if (timeOut > 0) {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    taskCallBack1.onNext();
                }
            }, timeOut);
        }
        mTask.startRun(taskCallBack1);
    }

    @Override
    public void setStop(boolean stop) {
        super.setStop(stop);
        if (stop){
            mTask.setStop(true);
        }
    }
}
